import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_core_widget/utils/ex/kq_ex.dart';
import 'package:kq_flutter_core_widget/utils/file_preview_util.dart';
import 'package:kq_flutter_core_widget/widgets/imageBox/kq_image_box.dart';
import 'package:kq_flutter_widgets/theme/kq_theme_manager.dart';
import 'package:kq_flutter_core_widget/widgets/button/kq_ink_well.dart';
import 'package:kq_flutter_widgets/widgets/divider/kq_divider.dart';
import 'package:kq_flutter_core_widget/widgets/image/kq_image.dart';
import 'package:kq_flutter_widgets/widgets/image/kq_print_image.dart';
import 'package:kq_flutter_widgets/widgets/overflowBox/kq_over_flow_box.dart';
import 'package:kq_flutter_widgets/widgets/wrapFlow/kq_auto_column_flow.dart';

import '../../resources/kq_theme_colors.dart';

enum DividePosition {
  /// 头部
  top,

  /// 底部
  bottom
}

class KqCard extends StatefulWidget {
  /// 图片url
  final String? url;

  /// 图片类型
  final ImageType imgType;

  /// 默认图片
  final String defaultPic;

  /// 多张模具/产品图片,用于图片预览
  final String? allPic;

  /// 标题
  final String? title;

  /// 副标题图片
  final String? subTitleImg;

  /// 副标题
  final String? subTitle;

  /// 第二个副标题图片
  final String? subSecondTitleImg;

  /// 第二个副标题
  final String? subSecondTitle;

  /// 分隔线位置,未设置就不显示
  final DividePosition? dividePosition;

  /// 分隔线高度 默认：8.r
  final double? divideHeight;

  /// 底部widget,和bottomBtns实现一种
  final Widget? bottomBtnsView;

  /// 底部widget,和bottomBtnsView实现一种
  final List<Widget>? bottomBtns;

  /// tags 标签
  final List<Widget>? tags;

  /// 印章类型，使用[KqPrintType]
  final KqPrintType? printType;

  /// 卡片信息内容个数
  final int totalCount;

  /// 行数
  final int Function()? rowCountCallback;

  ///每行的列数
  final int Function(int row)? renderCrossAxisCountCallback;

  ///icon
  final String Function(int row, int column)? renderIconPathCallback;

  ///Text
  final String Function(int row, int column)? renderTextCallback;

  /// 指定位置的右边widget自定义
  final Widget? Function(int row, int column)? renderWidgetCallback;

  ///Text行数
  final int Function(int row, int column) renderTextMaxLineCallback;

  /// 点击
  final void Function()? onTap;

  const KqCard(
      {this.url,
      required this.imgType,
      required this.defaultPic,
      this.allPic,
      this.title,
      this.subTitleImg,
      this.subTitle,
      this.subSecondTitleImg,
      this.subSecondTitle,
      this.dividePosition,
      this.divideHeight,
      this.bottomBtnsView,
      this.bottomBtns,
      this.tags,
      this.printType,
      this.onTap,
      required this.totalCount,
      required this.renderCrossAxisCountCallback,
      this.renderIconPathCallback,
      this.renderTextCallback,
      this.renderWidgetCallback,
      required this.rowCountCallback,
      required this.renderTextMaxLineCallback,
      super.key});

  @override
  State<KqCard> createState() => _KqCardState();
}

class _KqCardState extends State<KqCard> {
  double widgetWidth = KqScreenUtil().screenWidth;

  /// 水平间距
  double spacing = 8.r;

  /// 垂直方向间距
  double runSpacing = 6.r;

  @override
  Widget build(BuildContext context) {
    return Container(
      color: KqThemeColors.bgWhite,
      child: KqInkWell(
        onTap: () {
          widget.onTap?.call();
        },
        enableRipple: false,
        child: renderContent(),
      ),
    );
  }

  Widget renderContent() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        Visibility(
            visible: widget.dividePosition != null &&
                widget.dividePosition == DividePosition.top,
            child: KqDivider(
              height: widget.divideHeight ?? 8.r,
            )),
        Container(
          margin: EdgeInsets.only(top: 12.r),
          padding: EdgeInsets.symmetric(horizontal: 16.r),
          child: Row(
            children: [
              InkWell(
                onTap: () {
                  if (widget.allPic.isNotNullOrEmpty) {
                    List urls = widget.allPic!.split(',');
                    if (urls.isNotNullOrEmpty) {
                      if (urls.length == 1) {
                        /// 单张预览
                        FilePreviewUtil.previewSingleImg(ImageUrl(
                            imageType: widget.imgType, url: widget.url ?? ''));
                      } else {
                        /// 多张预览
                        List<ImageUrl> imgs = urls
                            .map((e) =>
                                ImageUrl(imageType: widget.imgType, url: e))
                            .toList();
                        FilePreviewUtil.previewImg(imgs);
                      }
                    } else {
                      FilePreviewUtil.previewSingleImg(ImageUrl(
                          imageType: widget.imgType, url: widget.url ?? ''));
                    }
                  } else {
                    FilePreviewUtil.previewSingleImg(ImageUrl(
                        imageType: widget.imgType, url: widget.url ?? ''));
                  }
                },
                child: _buildImage(widget.imgType),
              ),
              Expanded(child: renderTitleInfo()),
            ],
          ),
        ),
        SizedBox(
          height: 14.r,
        ),
        Container(
          margin: EdgeInsets.only(bottom: 12.r),
          padding: EdgeInsets.symmetric(horizontal: 16.r),
          child: renderWrapFlowContent(),
        ),
        Visibility(
            visible: widget.bottomBtns != null || widget.bottomBtnsView != null,
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 16.r),
              child: const KqDivider(),
            )),
        Visibility(
            visible: widget.bottomBtns != null || widget.bottomBtnsView != null,
            child: renderBottomBtns()),
        Visibility(
            visible: widget.dividePosition != null &&
                widget.dividePosition == DividePosition.bottom,
            child: KqDivider(
              height: widget.divideHeight ?? 8.r,
            )),
      ],
    );
  }

  Widget _buildImage(ImageType imageType) {
    return KqImage.custom(
        imageType: imageType,
        radius: 4.r,
        url: widget.url ?? '',
        width: 44.r,
        height: 44.r,
        fit: BoxFit.cover,
        errorImage: widget.defaultPic);
  }

  List<Widget> renderTags() {
    List<Widget> tags = [];
    if (widget.tags != null) {
      for (var i = 0; i < widget.tags!.length; i++) {
        tags.add(widget.tags![i]);
        if (i != widget.tags!.length - 1) {
          tags.add(SizedBox(
            width: 6.r,
          ));
        }
      }
    }
    return tags;
  }

  Widget renderTitleInfo() {
    String title = widget.title ?? '';
    return Container(
      margin: EdgeInsets.only(left: 12.r),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(
                  child: Text(title.ellipsis(),
                      style: TextStyle(
                          fontSize:
                              KqThemeManager.getFormConfig().titleFontSize ??
                                  14.sp,
                          color: KqThemeColors.text26),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis)),
              Visibility(
                  visible: widget.tags != null,
                  child: Container(
                    margin: EdgeInsets.only(top: 3.r),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: renderTags(),
                    ),
                  )),
            ],
          ),
          renderSubTitleInfo()
        ],
      ),
    );
  }

  Widget renderSubTitleInfo() {
    String? subTitle = widget.subTitle ?? '';
    String? subSecondTitle = widget.subSecondTitle ?? '';
    return Row(
      children: [
        Visibility(
            visible: widget.subTitleImg != null ? true : false,
            child: Image.asset(
              widget.subTitleImg ?? '',
              width: 12.r,
              height: 12.r,
            )),
        Visibility(
            visible: subTitle != '',
            child: SizedBox(
              width: widget.subTitleImg != null ? 8.r : 12.r,
            )),
        Visibility(
            visible: subTitle != '' && widget.subSecondTitleImg != null,
            child: Container(
              constraints: BoxConstraints(maxWidth: 120.r),
              child: Text(
                subTitle.ellipsis(),
                style: TextStyle(
                    fontSize:
                        KqThemeManager.getFormConfig().contentFontSize ?? 12.sp,
                    color: KqThemeColors.text59),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            )),
        Visibility(
            visible: subTitle != '' && widget.subSecondTitleImg == null,
            child: Expanded(
                child: Text(
              subTitle.ellipsis(),
              style: TextStyle(
                  fontSize:
                      KqThemeManager.getFormConfig().contentFontSize ?? 12.sp,
                  color: KqThemeColors.text59),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ))),
        Visibility(
            visible: widget.subSecondTitleImg != null ? true : false,
            child: Image.asset(
              widget.subSecondTitleImg ?? '',
              width: 12.r,
              height: 12.r,
            )),
        Visibility(
            visible: subSecondTitle != '' && widget.subSecondTitleImg != null,
            child: SizedBox(
              width: widget.subSecondTitleImg != null ? 8.r : 12.r,
            )),
        Visibility(
            visible: subSecondTitle != '',
            child: Expanded(
              // constraints: BoxConstraints(maxWidth: 120.r),
              child: Text(
                subSecondTitle.ellipsis(),
                style: TextStyle(
                    fontSize:
                        KqThemeManager.getFormConfig().contentFontSize ?? 12.sp,
                    color: KqThemeColors.text59),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            )),
      ],
    );
  }

  Widget renderWrapFlowContent() {
    if (widget.printType != null) {
      return KqOverFlowBox(
          referenceWidget: KqAutoColumnFlow(
              spacing: spacing,
              runSpacing: runSpacing,
              fontSize: 12.r,
              iconWidth: 12.r,
              totalCount: widget.totalCount,
              renderCrossAxisCountCallback: widget.renderCrossAxisCountCallback,
              renderIconPathCallback: widget.renderIconPathCallback,
              renderTextCallback: widget.renderTextCallback,
              rowCountCallback: widget.rowCountCallback,
              renderTextMaxLineCallback: widget.renderTextMaxLineCallback),
          overflowBoxWidget: KqPrintImage(printType: widget.printType!),
          visible: true,
          position: BoxToReferencePosition.bottom,
          alignment: Alignment.bottomRight,
          maxWidth: 44.r,
          maxHeight: 44.r);
    }
    return KqAutoColumnFlow(
        spacing: spacing,
        runSpacing: runSpacing,
        fontSize: 12.r,
        iconWidth: 12.r,
        totalCount: widget.totalCount,
        renderCrossAxisCountCallback: widget.renderCrossAxisCountCallback,
        renderIconPathCallback: widget.renderIconPathCallback,
        renderTextCallback: widget.renderTextCallback,
        rowCountCallback: widget.rowCountCallback,
        renderWidgetCallback: widget.renderWidgetCallback,
        renderTextMaxLineCallback: widget.renderTextMaxLineCallback);
  }

  Widget renderBottomBtns() {
    if (widget.bottomBtnsView != null) {
      return widget.bottomBtnsView ?? Container();
    } else if (widget.bottomBtns != null) {
      List<Widget> btns = [];
      for (var i = 0; i < widget.bottomBtns!.length; i++) {
        btns.add(widget.bottomBtns![i]);
        if (widget.bottomBtns!.length - 1 != i) {
          btns.add(SizedBox(
            width: 8.r,
          ));
        }
      }
      return Container(
        // height: 48.r,
        padding: EdgeInsets.symmetric(horizontal: 16.r, vertical: 8.r),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.end,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: btns,
        ),
      );
    }
    return Container();
  }
}
